package com.ming.common.liteflow.core.el.bus;

import cn.hutool.core.util.StrUtil;
import com.ming.common.liteflow.core.node.IvyCmp;
import com.yomahub.liteflow.builder.el.ELBus;
import com.yomahub.liteflow.builder.el.ELWrapper;
import com.yomahub.liteflow.builder.el.IfELWrapper;
import com.yomahub.liteflow.builder.el.ThenELWrapper;

public class ELBusIf {

    private ELWrapper wrapper;

    public static ELBusIf NEW(){
        return new ELBusIf();
    }

    public ELBusIf node(IvyCmp info){
        Object trueOpt = info.getCmpTrueOptEL() != null ? info.getCmpTrueOptEL() : info.getCmpTrueOpt();
        Object falseOpt = info.getCmpFalseOptEL() != null ? info.getCmpFalseOptEL() : info.getCmpFalseOpt();
        IfELWrapper ifELWrapper = ELBus.ifOpt(ELBusNode.NEW().node(info).toELWrapper(), trueOpt, falseOpt);
        if(StrUtil.isNotBlank(info.getCmpId())){
            ifELWrapper.id(info.getCmpId());
        }
        if(StrUtil.isNotBlank(info.getCmpTag())){
            ifELWrapper.tag(info.getCmpTag());
        }
        if(StrUtil.isNotBlank(info.getCmpPre()) || StrUtil.isNotBlank(info.getCmpFinallyOpt())){
            ThenELWrapper then = ELBus.then(ifELWrapper);
            if(StrUtil.isNotBlank(info.getCmpPre())){
                then.pre(info.getCmpPre());
            }
            if(StrUtil.isNotBlank(info.getCmpFinallyOpt())){
                then.finallyOpt(info.getCmpFinallyOpt());
            }
            if(info.getCmpMaxWaitSeconds() != null){
                then.maxWaitSeconds(info.getCmpMaxWaitSeconds());
            }
            wrapper = then;
        }else{
            if(info.getCmpMaxWaitSeconds() != null){
                ifELWrapper.maxWaitSeconds(info.getCmpMaxWaitSeconds());
            }
            wrapper = ifELWrapper;
        }
        return this;
    }

    public String toEL(){
        return wrapper.toEL();
    }

    public String toEL(boolean format){
        return wrapper.toEL(format);
    }

    public ELWrapper toELWrapper(){
        return wrapper;
    }

}
